<template>
  <a-card>
    <div>
      <a-form layout="horizontal">
        <div>
          <a-row >
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择园区" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.farmId" placeholder="请选择园区" @change="farmChange">
                  <a-select-option
                      v-for="(item, index) in farmList"
                      :key="index" :value="item.FarmId">
                    {{item.FarmName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <div style="margin: 3px 0 0 8px;">
                <a-button type="primary" @click="search">查询</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>
    <div>
      <a-space class="operator">
        <a-button @click="visible = true" type="primary">新建</a-button>
      </a-space>
      <standard-table :rowKey="(data, index) => index"
               :columns="columns" :data-source="devVisualList" bordered>
        <div slot="action" slot-scope="{text, record}" >
          <a style="margin-right: 8px" @click="editRecard(record)">
            <a-icon type="edit"/> 编辑
          </a>
<!--          <a style="margin-right: 8px" @click="editVisual(record)">-->
<!--            <a-icon type="edit"/>编辑组态-->
<!--          </a>-->
          <a style="margin-right: 8px" @click="showVisual(record)">
            <a-icon type="eye"/> 预览
          </a>
          <a style="margin-right: 8px" @click="showShare(record)">
            <a-icon type="copy"/> 分享链接
          </a>
          <a-popconfirm title="确定删除?" @confirm="delRecord(record)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a href="#" style="margin-right: 8px; color: #f5222d"><a-icon type="delete" />删除</a>
          </a-popconfirm>
        </div>
      </standard-table>
    </div>
    <!-- 新增弹窗  -->
    <a-modal
        title="新建大屏"
        width="900px"
        :visible="visible"
        @ok="confirm"
        @cancel="colseModal">
      <a-form-model
          ref="farmForm"
          :model="addData"
          :rules="addRules"
          :label-col="{span: 3}"
          :wrapper-col="{span: 20}">
        <a-form-model-item label="选择园区"  prop="farmId">
          <a-select v-model="addData.farmId" placeholder="请选择园区" @change="modalChange">
            <a-select-option
                v-for="(item, index) in farmList"
                :key="index" :value="item.FarmId">
              {{item.FarmName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="大屏名称" prop="name">
          <a-input v-model="addData.name" type="text" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
        title="分享链接"
        width="900px"
        :visible="share"
        centered
        okText="一键复制"
        :footer="null"
        @cancel="closeShare">
      <a-form-model
          ref="farmForm"
          :label-col="{span: 3}"
          :wrapper-col="{span: 20}">
        <a-form-model-item label="免密链接" prop="share_link">
          <a-input v-model="share_url1" type="text" >
            <div slot="suffix" style="background-color: #fff;padding-left: 10px;cursor: pointer" @click="copyUrl($event,share_url1)">
              <a-icon type="copy"/>
              <span style="margin-left: 5px">复制</span>
            </div>
          </a-input>
        </a-form-model-item>
        <a-form-model-item label="分享链接" prop="share_link">
          <a-input v-model="share_url2" type="text" >
            <div slot="suffix" style="background-color: #fff;padding-left: 10px;cursor: pointer" @click="copyUrl($event,share_url2)">
              <a-icon type="copy"/>
              <span style="margin-left: 5px">复制</span>
            </div>
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import {delFarm, farmIdList, farmSave} from "@/services/largeScreen";
import {list as farmList} from '@/services/farm'
import {message} from "ant-design-vue";
import StandardTable from '@/components/table/StandardTable'
import Clipboard from 'clipboard';

// 表格
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '园区名称',
    dataIndex: 'farmName',
    key: 'farmName',
  },
  {
    title: '地块名称',
    dataIndex: 'greenHouseName',
    key: 'greenHouseName',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '400px',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: "Disposition",
  components: {
    StandardTable
  },
  data() {
    return {
      // 园区
      query: {
        farmId: '',
        farmName: ''
      },
      farmList: [],
      // 新增弹窗
      visible:false,
      share:false,
      share_url1:'',
      share_url2:'',
      // 表单
      addData:{
        name:'',
        farmId:'',
        farmName:''
      },
      addRules: {
        name: [
          { required: true, message: '请输入大屏名称', trigger: 'blur' },
        ],
        farmId: [
          { required: true, message: '请选择园区', trigger: 'change' },
        ],
      },
      columns: columns,
      // 页面
      devVisualList: [],
      // 复制
      clipboard:null
    }
  },
  created() {
    this.getFarmList()
  },
  methods: {
    // 获取园区列表
    async getFarmList() {
      let res = await farmList()
      this.farmList = res.Data
    },
    // 查询选择园区
    farmChange(e) {
      this.query.farmId = e
      this.addData.farmId = e
      let item = this.farmList.filter(function (item) {
        return item.FarmId === e;
      })[0]
      this.query.farmName = item.FarmName
      this.addData.farmName = item.FarmName
    },
    // 弹窗选择园区
    modalChange(e) {
      this.addData.farmId = e
      let item = this.farmList.filter(function (item) {
        return item.FarmId === e;
      })[0]
      this.addData.farmName = item.FarmName
    },
    // 关闭弹窗
    colseModal(){
      this.visible = false
      this.$refs.farmForm.resetFields();
    },
    closeShare(){
      this.share=false;
      this.share_url1='';
      this.share_url2='';
    },
    // 复制链接
    copyUrl(e,text){
      const clipboard = new Clipboard(e.target, { text: () => text })
      clipboard.on('success', e => {
        this.$message.success('复制成功');
        // 释放内存
        clipboard.off('error')
        clipboard.off('success')
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.$message.success('该浏览器不支持自动复制');
        // 释放内存
        clipboard.off('error')
        clipboard.off('success')
        clipboard.destroy()
      })
      clipboard.onClick(e)
    },
    // 确定新增
    confirm(){
      let _this = this
      this.$refs.farmForm.validate(async valid => {
        if (valid) {
          let res = await farmSave({
            "farmId": _this.addData.farmId,
            "farmName": _this.addData.farmName,
            "name": _this.addData.name,
          })
          if(res.resp_code === 0){
            // 添加成功后，将列表的园区选择当前添加的园区，执行查询
            message.success(res.resp_msg);
            _this.query.farmId = _this.addData.farmId
            _this.query.farmName = _this.addData.farmName
            _this.visible = false
            _this.$refs.farmForm.resetFields();
            _this.search()
          }else {
            message.error(res.resp_msg);
          }
        }
      })
    },
    // 查询园区下的大屏
    async search() {
      let res = await farmIdList([this.query.farmId])
      if(res.resp_code === 0){
        this.devVisualList = res.datas
      }
    },
    //展示分享链接
    showShare(row){
      this.share=true;
      this.share_url1=`${process.env.VUE_APP_API_BASE_URL_LARGE}by/?id=${row.id}&USER_MOBILE=${localStorage.getItem('USER_MOBILE')}&PASSWORD=${this.toCode(localStorage.getItem('PASSWORD'))}`;
      this.share_url2=`${process.env.VUE_APP_API_BASE_URL_LARGE}by/?id=${row.id}`
    },
    // 预览大屏
    showVisual(row) {
      window.open(`${process.env.VUE_APP_API_BASE_URL_LARGE}by/?id=${row.id}&USER_MOBILE=${localStorage.getItem('USER_MOBILE')}&PASSWORD=${this.toCode(localStorage.getItem('PASSWORD'))}`);
    },
    // 基础信息
    editRecard(row) {
      window.open(`${process.env.VUE_APP_API_BASE_URL_LARGE}by/?id=${row.id}&type=edit&USER_MOBILE=${localStorage.getItem('USER_MOBILE')}&PASSWORD=${this.toCode(localStorage.getItem('PASSWORD'))}`);
    },
    // 编辑组态
    editVisual(row)  {
      window.open(`${process.env.VUE_APP_API_BASE_URL_LARGE}by/?id=${row.id}&type=visual&USER_MOBILE=${localStorage.getItem('USER_MOBILE')}&PASSWORD=${this.toCode(localStorage.getItem('PASSWORD'))}`);
    },
    // 删除
    async delRecord(row) {
      let res = await delFarm(row.id)
      if(res.resp_code === 0){
        // 添加成功后，将列表的园区选择当前添加的园区，执行查询
        message.success(res.resp_msg);
        this.search()
      }else {
        message.error(res.resp_msg);
      }
    },

    // 组态默认登录加密
    toCode(str) {
      // 加密字符串
      // 定义密钥，36个字母和数字
      const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      const st = key.length // 获取密钥的长度
      const a = key.split('') // 把密钥字符串转换为字符数组
      let s = ''
      let b
      let b1
      let b2
      let b3 // 定义临时变量
      for (let i = 0; i < str.length; i++) { // 遍历字符串
        b = str.charCodeAt(i) // 逐个提取每个字符，并获取Unicode编码值
        b1 = b % st // 求Unicode编码值得余数
        b = (b - b1) / st // 求最大倍数
        b2 = b % st // 求最大倍数的于是
        b = (b - b2) / st // 求最大倍数
        b3 = b % st // 求最大倍数的余数
        s += a[b3] + a[b2] + a[b1] // 根据余数值映射到密钥中对应下标位置的字符
      }
      return s // 返回这些映射的字符
    },
  }
}
</script>

<style scoped lang="less">
.operator{
  margin-bottom: 18px;
}
</style>
